package com.tgl.handler;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author tonggl
 * @date 2024/7/22 16:57
 * @description 响应Ping服务的请求，根据参数返回对应的结果
 */
@Component
public class PongHandler {

    private final AtomicInteger counter = new AtomicInteger(0);
    private long lastReset = System.currentTimeMillis();

    public Mono<ServerResponse> receiveMsg(String parameter) {
        boolean flag = tryLock();

        if (!flag) {
            return
                    ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).syncBody("Too Many Requests");
        }

        if (parameter == null || !"Hello".equals(parameter)) {
            return ServerResponse.status(HttpStatus.OK).syncBody("Parameter is incorrect");
        }
        return ServerResponse.status(HttpStatus.OK).syncBody("World");
    }

    public boolean tryLock() {
        long now = System.currentTimeMillis();
        long secondsSinceLastReset = (now - lastReset) / 1000;

        if (secondsSinceLastReset > 0) {
            counter.set(0);
            lastReset = now;
        }

        if (counter.incrementAndGet() > 1) {
            return false;
        }
        return true;
    }

}
